﻿using System.Collections.Generic;
using AutoMapper;
using VMWorkshop.Domain;
using VMWorkshop.Web.Models;

namespace VMWorkshop.Web.Models.ViewModels
{
    public class AjaxViewModel
    {
        private IList<ProductListView> _products = null;
        private IProductRepository _repository = null;
        private bool _isPersistActionComplete = false;

        public bool IsPersistActionComplete
        {
            get { return this._isPersistActionComplete; }
        }

        public IList<ProductListView> Products
        {
            get 
            {
                if (this._products == null)
                {
                    var products = this._repository.GetAll();
                    this._products = Mapper.Map<IList<Product>, IList<ProductListView>>(products);
                }
                return this._products;
            }
        }

        public AjaxViewModel(IProductRepository repository)
        {
            this._repository = repository;
        }

        internal ProductEditView GetProductById(int productId)
        {
            var product = this._repository.GetProductById(productId);
            return ProductEditView.ToProductEditView(product);
        }

        internal void PersistChanges(ProductEditView editView)
        {
            Product newProduct = ProductEditView.ToProduct(editView);
            Product oldProduct = this._repository.GetProductById(newProduct.ProductId);
            oldProduct = Mapper.Map<Product, Product>(newProduct, oldProduct);
            this._repository.Persist(oldProduct);
            this._isPersistActionComplete = true;
        }
    }
}
